package org.wltea.analyzer.dic;

import java.io.IOException;

import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpHead;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

/**
 * 远程调用文件并定时检查更新
 * @createTime 2017-02-22
 */
public class Monitor implements Runnable {

	  private static CloseableHttpClient httpclient = HttpClients.createDefault();
	    private String last_modified;
	    private String eTags;
	    private String location;

	    public Monitor(String location) {
	        this.location = location;
	        this.last_modified = null;
	        this.eTags = null;
	    }

	    /**
	     *  监控流程：
	     *  1.向词库服务器发送head请求
	     *  2.从响应中获取 LAST_MODIFIED、eTags字段值,判断是否发送变化
	     *  3.如果未发生变化,休眠1min
	     *  4.如果有变化,重新加载词典
	     *  5.休眠1min,返回第1步
	     * 
	     * 
	     */
	    @Override
	    public void run() {
	        RequestConfig rc = RequestConfig.custom().setConnectionRequestTimeout(10000).setConnectTimeout(10000).setSocketTimeout(15000).build();
	        HttpHead head = new HttpHead(this.location);
	        head.setConfig(rc);
	        if (this.last_modified != null) {
	            head.setHeader("If-Modified-Since", this.last_modified);
	        }
	        CloseableHttpResponse response = null;
	        try {
	            response = httpclient.execute(head);
	            if (response.getStatusLine().getStatusCode() == 200) {
	            	
	            	String _last_modified=response.getLastHeader("Last-Modified").getValue();
	            	if(last_modified!=null){
	            		 DictionaryRemote.getSingleton().reLoadMainDict();
	            	}
	            	this.last_modified = _last_modified;
	            	
	            } else if (response.getStatusLine().getStatusCode() != 304) {
	                System.err.println("remote_ext_dict " + this.location + " return bad code " + response.getStatusLine().getStatusCode() + "");
	            }
	        } catch (Exception e) {
	        	e.getStackTrace();
	            System.err.println("IK remote_ext_dict error!");
	        } finally {
	            try {
	                if (response != null)
	                    response.close();
	            } catch (IOException e) {
	                e.printStackTrace();
	            }
	        }
	    }
	
}
